#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/10 下午8:01
# @Author  : jize.liu
# @File    : mian.py
# @声明     : 版权由 刘继泽 所有,如有疑问，需要帮助请联系刘继泽
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
    QMetaObject, QObject, QPoint, QRect,
    QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
    QFont, QFontDatabase, QGradient, QIcon,
    QImage, QKeySequence, QLinearGradient, QPainter,
    QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QAbstractItemView, QMenu,QFileDialog,QApplication, QComboBox, QFormLayout,QMessageBox,
    QGridLayout, QHBoxLayout, QHeaderView, QLabel,
    QLayout, QLineEdit, QMainWindow, QPushButton,
    QSizePolicy, QTreeWidget, QTreeWidgetItem, QVBoxLayout,
    QWidget)
from Mov_Merger_PySide_UI import Ui_MainWindow
import os,json,sys
class mov_merger (QMainWindow,Ui_MainWindow) :
    def __init__(self) :
        super (mov_merger, self).__init__ ()
        self.setupUi (self)
        self.__ui__ ()

    def __ui__(self) :
        '''
        print (CreateDecrypt.Getregistry ())
        if int (CreateDecrypt.Getregistry ()) <= 0 :
            QMessageBox.warning (Dialog , "警告对话框" , "注册时间已到期" , QMessageBox.Ok)
            return
        elif int (CreateDecrypt.Getregistry ()) > 0 and int (CreateDecrypt.Getregistry ()) <= 3 :
            QMessageBox.warning (Dialog , "警告对话框" , "注册时间还有" + str (CreateDecrypt.Getregistry ()) + "天到期" , QMessageBox.Ok)
        '''
        self.Del_pushButton.clicked.connect (self.Del_pushButton_clicked)
        self.__QMenu ()

        # 创建添加按钮信号事件
        self.Add_pushButton.clicked.connect (self.Add_pushButton_clicked)
        # 创建合成按钮信号事件
        self.Merger_pushButton.clicked.connect (self.Merger_pushButton_clicked)

        Path = "R:/"
        self.Project_comboBox.addItems (os.listdir (Path))
        self.Project_comboBox.activated.connect (lambda *args : self.Project_select (Path))

    def __QMenu(self):
        # 创建QMenu信号事件
        self.AllMov_treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.AllMov_treeWidget.customContextMenuRequested.connect(self.showMenu)
        self.create_rightmenu()

    def Del_pushButton_clicked(self):
        select_MergerItems = self.Merger_treeWidget.selectedItems()  # 获取所有选中项
        for select_MergerItem in select_MergerItems:  # 遍历选中项节点
            rootIndex = self.Merger_treeWidget.indexOfTopLevelItem(select_MergerItem)  # 获取选中项位数
            self.Merger_treeWidget.takeTopLevelItem(rootIndex)  # 按位数删除

    def showMenu(self, pos):
        # pos 鼠标位置
        # print(pos)
        # 菜单显示前,将它移动到鼠标点击的位置
        self.contextMenu.exec_(QCursor.pos())  # 在鼠标位置显示

        # 创建右键菜单函数

    def create_rightmenu(self):
        # 菜单对象
        self.contextMenu = QMenu(self.AllMov_treeWidget)
        self.CP = self.contextMenu.addAction('导出xls')
        self.JQ = self.contextMenu.addAction('剪切')
        self.NT = self.contextMenu.addAction('粘贴')
        # 事件绑定
        self.CP.triggered.connect(lambda *args: self.getFileOutPath())
        self.JQ.triggered.connect(self.Event)
        self.NT.triggered.connect(self.Event)

    def getFileOutPath(self):
        # app = QApplication([])
        print("************************************")
        FileOutPath = QFileDialog.getExistingDirectory(QMainWindow(), "选择文件夹")  # 选择目录，返回选中的路径
        # self.Out_Line.setText(FileOutPath)
        if len(FileOutPath) == 0:
            return
        print(FileOutPath)
        self.Export_table(FileOutPath)

    def Export_table(self, FileOutPath):

        Fileinfo = {}
        for AllMovItem in range(self.AllMov_treeWidget.topLevelItemCount()):
            AllMov_QTreeWidgetItem = (self.AllMov_treeWidget.topLevelItem(AllMovItem))
            info = {}
            infoPath = (AllMov_QTreeWidgetItem.text(1).replace('movies', 'info'))
            if os.path.exists(infoPath):
                infoPathsplit = infoPath.split('/')
                File = infoPath + '/' + infoPathsplit[3] + '_' + infoPathsplit[4] + '_' + infoPathsplit[
                    5] + '_ani' + "-publishInfo.json"
                # print (os.path.exists(File))
                if os.path.exists(File):
                    '''    
                    matchObj = (re.search("([a-z][a-z][0-9][0-9][0-9]_[a-z][a-z][0-9][0-9][0-9]_[a-z][a-z][a-z][a-z][0-9][0-9][0-9][a-z]_[a-z][a-z][a-z]-publishInfo.json)",infoFile))
                    print (matchObj.group(1))
                    if matchObj:
                    '''
                    with open(File, 'r') as fp:
                        file_content = json.load(fp)
                        # print(file_content["TotalFrames"])
                        # print(file_content["date"])
                        info["TotalFrames"] = str(file_content["TotalFrames"])
                        info["date"] = file_content["date"]
                        Fileinfo[str(AllMov_QTreeWidgetItem.text(0))] = info
                else:
                    info["TotalFrames"] = "None"
                    info["date"] = "None"
                    Fileinfo[str(AllMov_QTreeWidgetItem.text(0))] = info
            else:
                info["TotalFrames"] = "None"
                info["date"] = "None"

                Fileinfo[str(AllMov_QTreeWidgetItem.text(0))] = info
        # print (Fileinfo)
        path = FileOutPath + '/' + self.J_name_C + ".json"
        with open(path, 'w') as fp:
            json.dump(Fileinfo, fp)

    def Event(self):
        QMessageBox.information(self.contextMenu, "提示：", '   您选择了' + self.contextMenu.sender().text())

    def Add_pushButton_clicked(self):
        select_AddItems = self.AllMov_treeWidget.selectedItems()
        for select_AddItem in select_AddItems:
            # select_AddItem = self.AllMov_treeWidget.currentItem()
            # print (select_AddItem.text(0),select_AddItem.text(1))
            # self.Merger_treeWidget.addItem(select_AddItem.text(0))
            root = QTreeWidgetItem(self.Merger_treeWidget)
            root.setText(0, select_AddItem.text(0))
            root.setText(1, select_AddItem.text(1))

    def Merger_pushButton_clicked(self):
        rvinfo = "GTOa (4)\n"
        self.PlayRV = []

        # 获取treeWidget下Item方法
        for tem in range(self.Merger_treeWidget.topLevelItemCount()):
            print(tem)
            QTreeWidgetItem = (self.Merger_treeWidget.topLevelItem(tem))
            self.PlayRV.append(QTreeWidgetItem.text(1) + '/' + QTreeWidgetItem.text(0))

        '''
        Merger_AddItems = self.Merger_treeWidget.selectedItems()
        for Merger_AddItem in Merger_AddItems:
            print(Merger_AddItem.text(0))
            self.PlayRV.append(Merger_AddItem.text(1) +'/' +  Merger_AddItem.text(0))

         '''
        for i in range(len(self.PlayRV)):
            # print str (i)
            rvinfo += "sourceGroup" + str(
                i) + "_source : RVFileSource (1)\n{\n\tmedia\n\t{\n\tstring movie =" + '"' + self.PlayRV[
                          i] + '"' + "\n\t}\n}\n"
        # print ('88888888888888888888')
        # print (rvinfo)

        with open('D:/rvinfo.rv', 'w') as f:
            f.write(rvinfo)
        import subprocess
        subprocess.Popen([r"C:/Progra~1/ShotGrid/RV-2022.0.0/bin/rv.exe", r"D:/rvinfo.rv"])
        #subprocess.Popen([r"C:/Progra~1/Shotgun/RV-7.2.5/bin/rv.exe", r"D:/rvinfo.rv"])

    def Project_select(self, Path):

        self.Class_comboBox.clear()

        self.Class_comboBox.addItems(os.listdir(Path + self.Project_comboBox.currentText()))
        self.Class_comboBox.activated.connect(lambda *args: self.Project_Class(Path, self.Project_comboBox.currentText()))

    def Project_Class(self, Path, P_Class):
        self.Class_comboBox.currentText()
        self.Project_treeWidget.clear()
        print("111111111111111111111111111")
        print(Path + P_Class + '/' + self.Class_comboBox.currentText())
        J = os.listdir(Path + P_Class + '/' + self.Class_comboBox.currentText())

        for J_List in J:
            if os.path.isdir(Path + P_Class + '/' + self.Class_comboBox.currentText()+"/"+J_List):
                # self.Project_treeWidget.setHeaderLabels(['Key', 'Value'])
                root = QTreeWidgetItem(self.Project_treeWidget)
                root.setText(0, J_List)
                self.Project_treeWidget.setColumnWidth(0, 200)
                C = os.listdir(Path + P_Class + '/' + self.Class_comboBox.currentText() + '/' + J_List)
                # 添加子节点
                for C_List in C:
                    if os.path.isdir(Path + P_Class + '/' + self.Class_comboBox.currentText() + '/' + J_List + '/'+C_List):
                        child2 = QTreeWidgetItem(root)
                        child2.setText(0, C_List)
                        child2.setText(1, Path + P_Class + '/' + self.Class_comboBox.currentText() + '/' + J_List)
                        child2.setIcon(0, QIcon('../picture/bag/bag3.jpg'))
        self.Project_treeWidget.clicked.connect(lambda *args: self.onClicked(Path + P_Class + '/' + self.Class_comboBox.currentText()))

    def onClicked(self, Path):
        self.AllMov_treeWidget.clear()
        item = self.Project_treeWidget.currentItem()
        # print('当前处于第%d行' % index.row())
        # print('Key=%s,value=%s' % (item.text(0), item.text(1)))
        # print (Path)
        if len(item.text(1)) == 0:
            self.J_Folder(Path, item.text(0))

        if len(item.text(1)) != 0:
            self.C_Folder(item.text(1), item.text(0))

    def J_Folder(self, J_Path, J_name):
        self.AllMov_treeWidget.clear()
        # print(len(self.AllMov_treeWidget.children()))
        self.J_name_C = J_name
        # print (J_Path + '/' +J_name)
        Notation = []
        print("22222222222222222222222222222222222222222222222222222222222")
        print (J_Path + '/' + J_name)
        for C_nameList in os.listdir(J_Path + '/' + J_name):
            if os.path.isdir(J_Path + '/' + J_name + '/' + C_nameList):
                for cam_name in os.listdir(J_Path + '/' + J_name + '/' + C_nameList):
                    if os.path.isdir(J_Path + '/' + J_name + '/' + C_nameList +'/' +  cam_name):
                        for mov_Folder in os.listdir(J_Path + '/' + J_name + '/' + C_nameList + '/' + cam_name):
                            for mov in os.listdir(J_Path + '/' + J_name + '/' + C_nameList + '/' + cam_name + '/' + mov_Folder):
                                if ".mov" in mov:
                                    if os.path.isfile(J_Path + '/' + J_name + '/' + C_nameList + '/' + cam_name + '/' + mov_Folder + '/' + mov):
                                        Notation.append(mov)
                                        root = QTreeWidgetItem(self.AllMov_treeWidget)
                                        root.setText(0, mov)
                                        root.setText(1,
                                                     J_Path + '/' + J_name + '/' + C_nameList + '/' + cam_name + '/' + mov_Folder)
                                        # self.Add_pushButton_clicked(J_Path + '/' + J_name + '/' + C_nameList + '/' + cam_name + '/' + mov_Folder,mov)
                                        # root.setCheckState(0, Qt.Unchecked)

        self.AllMov_lineEdit.setText(str(len(Notation)))

    def C_Folder(self, C_Path, C_name):
        self.AllMov_treeWidget.clear()
        print(C_Path + '/' + C_name)
        Notation = []
        for cam_name in os.listdir(C_Path + '/' + C_name):
            for mov_Folder in os.listdir(C_Path + '/' + C_name + '/' + cam_name):
                for mov in os.listdir(C_Path + '/' + C_name + '/' + cam_name + '/' + mov_Folder):
                    if ".mov" in mov:
                        if os.path.isfile(C_Path + '/' + C_name + '/' + cam_name + '/' + mov_Folder + '/' + mov):
                            Notation.append(mov)
                            root = QTreeWidgetItem(self.AllMov_treeWidget)
                            root.setText(0, mov)
                            root.setText(1, C_Path + '/' + C_name + '/' + cam_name + '/' + mov_Folder + '/' + mov)
                            # root.setCheckState(0, Qt.Unchecked)

        self.AllMov_lineEdit.setText(str(len(Notation)))

    # def Mov_Count(self):
    #    self.AllMov_treeWidget.


if __name__ == "__main__":
    app = QApplication (sys.argv)
    window = mov_merger ()
    window.show ()
    sys.exit (app.exec ())